<?php

namespace app\api\controller\Appoint;

use app\api\controller\Common;
use app\api\Logic\Campusclass\CampusClassCourseEvaluationLogic;
use app\api\Logic\Campusclass\CampusClassCourseSignLogic;
use app\api\model\CampusClassCourseCommentsModel;
use app\api\model\CampusClassCourseEvaluationModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

/**
 * 我的课表接口
 */
class MyCourse extends Common
{
    protected $noNeedLogin = ['*'];

    protected $campusClassCourseSignLogic;
    protected $campusClassCourseEvaluationLogic;

    public function _initialize()
    {
        parent::_initialize();
        $this->campusClassCourseSignLogic = new CampusClassCourseSignLogic();
        $this->campusClassCourseEvaluationLogic = new CampusClassCourseEvaluationLogic();
    }

    /**
     * 返回日期段内是否存在我的课程
     * @return void
     */
    public function myCourseByDate(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $startDate = isset($params['start_time']) && !empty($params['start_time']) ? date('Y-m-d',strtotime($params['start_time'])) : '';
            $endDate = isset($params['end_time']) && !empty($params['end_time']) ? date('Y-m-d',strtotime($params['end_time'])) : '';
            if(empty($startDate) || empty($endDate)){
                $this->error('时间不能为空');
            }

            //日期数组
            $dateAry = rangeToDays($startDate,$endDate,true);

            //获取日期段内涉及的课次
            $involveCourse = $this->campusClassCourseSignLogic->getInvolve($params['user_id'],strtotime($startDate),strtotime($endDate));

            $res = [];
            //循环日期，验证每一天是否存在我的课程
            foreach ($dateAry as $key => $date){
                $dateToTime = strtotime($date);

                $res[$key] = [
                    'date' => $date,
                    'time' => $dateToTime,
                    'is_exists' => false
                ];

                foreach ($involveCourse as $course){
                    if(strtotime(date('Y-m-d',$course['start_time'])) <= $dateToTime && strtotime(date('Y-m-d',$course['end_time'])) >= $dateToTime){
                        $res[$key]['is_exists'] = true;
                    }
                }
            }

            if(!empty($res)){
                $this->success('查询成功',$res);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 我的课表
     * @return void
     */
    public function myCourseList(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            //获取课程方式
            $getWay = $params['get_way'] ?? 1;

            if($getWay == 1){
                //日历模式
                $startTime = isset($params['start_time']) && !empty($params['start_time']) ? strtotime($params['start_time']) : '';
                $endTime = isset($params['end_time']) && !empty($params['end_time']) ? strtotime($params['end_time']) : '';
                if(empty($startTime) || empty($endTime)){
                    $this->error('时间不能为空');
                }

                //获取日期段内涉及的课次
                $involveCourse = $this->campusClassCourseSignLogic->getInvolve($params['user_id'],$startTime,$endTime);
            }else{
                //列表模式
                $type = $params['type'] ?? 1;   //1表示待上课程  2表示已上课程
                if($type == 1){
                    $status = [0,3];
                }else{
                    $status = [1,2,4];
                }

                //根据状态获取学员课次
                $involveCourse = $this->campusClassCourseSignLogic->getInvolveByStatus($params['user_id'],$status);
            }

            if(!empty($involveCourse)){
                $this->success('查询成功',$involveCourse);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 课次详情
     * @return void
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function courseInfo(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $signId = $params['sign_id'] ?? 0;
            if(empty($signId)){
                $this->error('请选择课次');
            }

            $info = $this->campusClassCourseSignLogic->getInfo($signId);
            if(!empty($info)){
                //获取课次评价
                $evaluation = CampusClassCourseEvaluationModel::where('type',2)
                    ->where('s_id',$signId)
                    ->field('id,score,comments,url_type,url,status,create_time')
                    ->find();
                $evaluation = objToArray($evaluation) ?? [];
                $info['evaluation'] = $evaluation;

                if(!empty($info['evaluation'])){
                    //获取对于评价的评论
                    $comments = CampusClassCourseCommentsModel::where('e_id',$evaluation['id'])
                        ->field('id,e_id,operate_type,operate_id,sup_id,content,create_time')
                        ->select();
                    $comments = objToArray($comments) ?? [];

                    $info['comments'] = $this->getChildComment($comments);
                }

                $this->success('查询成功',$info);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 获取课程课件
     */
    public function getPractice(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $signId = $params['sign_id'] ?? 0;
            if(empty($signId)){
                $this->error('请选择课次');
            }

            $info = $this->campusClassCourseSignLogic->getInfo($signId);
            if(!empty($info)){
                //获取课件信息
                $practiceInfo = !empty($info['date_info']['practice']) ? unserialize($info['date_info']['practice']) : [];

                $info['practiceInfo'] = $practiceInfo;
                $this->success('查询成功',$info);
            }
            $this->error('暂无数据');
        }
        $this->error('请求错误');
    }

    /**
     * 获取评价下评论
     * @param $comments
     * @param $parent_id
     * @param $level
     * @return array
     */
    public function getChildComment($comments, $parent_id = 0, $level = 0)
    {
        $newComments = [];

        foreach ($comments as $val) {
            if ($val['sup_id'] == $parent_id) {
                $val['level'] = $level;
                $val['childs'] = $this->getChildComment($comments, $val['id'], $level + 1);
                $newComments[] = $val;
            }
        }

        return $newComments;
    }

    /**
     * 学员评价课次
     * @return void
     */
    public function evaluationCourse(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $signId = $params['sign_id'] ?? 0;
            if(empty($signId)){
                $this->error('请选择课次');
            }

            //评价平均分，由前端计算后传递
            $score = $params['score'] ?? 0;
            //评语
            $comments = $params['comments'] ?? '';
            //文件类型
            $urlType = $params['url_type'] ?? 1;
            //文件路径
            $url = $params['url'] ?? '';

            //验证学员是否已评价该课程
            $isExists = $this->campusClassCourseEvaluationLogic->isExists($signId);
            if($isExists){
                $this->error('该课次已被评价');
            }

            //添加评价记录
            $res = CampusClassCourseEvaluationModel::insert([
                'type' => 2,
                's_id' => $signId,
                'score' => $score,
                'comments' => $comments,
                'url_type' => $urlType,
                'url' => $url,
                'create_time' => time()
            ]);
            if($res){
                $this->success('评价成功');
            }
            $this->error('评价失败');
        }
        $this->error('请求错误');
    }

    /**
     * 评论课次中的评价
     * @return void
     */
    public function comments(){
        if($this->request->isPost()){
            $params = $this->request->param();
            //验证数据
            $params = $this->verifyData($params);

            $evaluationId = $params['evaluation_id'] ?? 0;
            if(empty($evaluationId)){
                $this->error('评论ID必须');
            }

            $commentUserId = $params['comment_user_id'] ?? 0;
            if (empty($commentUserId)){
                $this->error('评论人ID必须');
            }

            $supId = $params['sup_id'] ?? 0;
            $content = $params['content'] ?? '';
            if(empty($content)){
                $this->error('评论内容必须');
            }

            //添加评论记录
            $res = CampusClassCourseCommentsModel::insert([
                'e_id' => $evaluationId,
                'operate_type' => 2,
                'operate_id' => $commentUserId,
                'sup_id' => $supId,
                'content' => $content,
                'create_time' => time()
            ]);
            if($res){
                $this->success('评价成功');
            }
            $this->error('评价失败');
        }
        $this->error('请求错误');
    }
}
